<?php


namespace app\cms\admin\controller;

use app\cms\model\adminLoginLogsModel;
use app\cms\model\replyModel;
use app\cms\model\resourcesModel;
use iflow\auth\Authorize\AuthAnnotation;
use iflow\fileSystem\lib\FileList;
use iflow\Response;
use iflow\Router\Controller;
use iflow\Router\implement\Request\{ GetMapping, DeleteMapping };

#[Controller('%cmsAdmin%/tool')]
class tool
{
    #[GetMapping]
    #[AuthAnnotation('file', '*')]
    public function getFiles(): Response
    {
        $query = resourcesModel::where([
            'resources_pwd' => '-1',
            'status' => 1,
        ]) -> paginate([
            'page' => request() -> getParams('page'),
            'list_rows' => 10
        ]);
        if ($query -> items()) {
            return message() -> success('查询成功', $query -> items(), [
                'count' => $query -> total(),
                'page' => $query -> lastPage()
            ]);
        }
        return message() -> nodata('暂无数据');
    }

    #[DeleteMapping('del_file/<?:resources_id>')]
    #[AuthAnnotation('file', 'fileWrite')]
    public function delFile(string $resources_id = ''): Response
    {
        return resourcesModel::deleteResources($resources_id);
    }

    #[GetMapping]
    #[AuthAnnotation('logs', 'adminUser')]
    public function getLoginLogs(): Response
    {
        $items = adminLoginLogsModel::where([
            'uid' => session('userInfo')['uid']
        ]) -> order('create_time', 'desc') -> paginate([
            'list_rows' => 8
        ]) -> items();
        return message() -> success('success', $items);
    }

    #[DeleteMapping('delete_reply/<?:reply_id>')]
    #[AuthAnnotation('reply', 'replyWrite')]
    public function deleteReply(string $reply_id, string $form_id): Response {
        return (new replyModel()) -> deleteReply($reply_id, $form_id);
    }

    #[DeleteMapping]
    #[AuthAnnotation('tool', 'clearCache')]
    public function clearCache(): Response {
        // 排除缓存目录
        $root = app() -> getRuntimePath();
        $ignore = [
            $root.'store'.DIRECTORY_SEPARATOR.'file',
            $root.'store'.DIRECTORY_SEPARATOR.'session',
            $root.'logs'
        ];
        $remove = (new FileList()) -> removeDir(
            $root,
            $ignore
        );
        return message() -> success(
            "清除缓存成功 共计 {$remove['dirCount']} 个文件夹 忽略 {$remove['ignoreCount']} 个文件夹"
        );
    }
}
